package main

import (
	"fmt"
	"flag"
	"gim/comm"
	log "github.com/golang/glog"
	"net"
	"time"
)

func main() {
	connect_host := flag.String("C", "127.0.0.1:8090", "-C 127.0.0.1:8090")
	uid := flag.Int64("U", 0, "-U 1")
	token := flag.String("T", "", "")
	device_id := flag.String("D", "", "device id")
	to := flag.Int64("To", 0, "-To 2")
	
	flag.Parse()
	
	comm.InitMessage()
	
	addr, err := net.ResolveTCPAddr("tcp", *connect_host)
	if err != nil {
		log.Fatal("resolve connect host err", err)
	}
	
	conn, err := net.DialTCP("tcp", nil, addr)
	defer conn.Close()
	
	conn.SetDeadline(time.Now().Add(60 * 6 * time.Second))
	
	auth_msg := new(comm.Message)
	auth_msg.Cmd = comm.MSG_AUTH_TOKEN
	auth_msg.Seq = comm.CurrentTimeMillis()
	auth_msg.Version = comm.DEFAULT_VERSION
	auth_msg.Body = &comm.AuthenticationToken{
		Uid	: *uid,
		Token : *token,
		Platform_id : 1,
		Device_id : *device_id,
	}
	
	//发起认证
	err = comm.SendMessage(conn, auth_msg)
	if err != nil {
		log.Fatal("client send auth err", err)
		return
	}
	m := comm.ReceiveMessage(conn)
	if m.Cmd != comm.MSG_AUTH_STATUS {
		log.Fatal("client receive auth status err")
		return
	}
	body := m.Body.(*comm.AuthenticationStatus)
	if body.Status != 0 {
		log.Fatal("client auth failed")
		return
	}
	
	go func() {
		for {
			msg := comm.ReceiveMessage(conn)
			if msg == nil {
				conn.Close()
				break;
			}
			
			fmt.Printf("%v\n", msg)
			fmt.Printf("%v\n", msg.Body)
		}	
	}()
	
	go func() {
		for {
			msg := new(comm.Message)
			msg.Cmd = comm.MSG_IM
			msg.Seq = comm.CurrentTimeMillis()
			msg.Version = comm.DEFAULT_VERSION
			msg.Body = &comm.IMMessage{
				Sender : *uid,
				Receiver : *to,
				Content : fmt.Sprintf("%d to %d", *uid, *to),
				Extra : "nice job",
			}
	
			err := comm.SendMessage(conn, msg)
			if err != nil {
				log.Fatal("client send msg failed", err)
				conn.Close()
				break;
			}
			time.Sleep(time.Second * 4)
		}	
	}()
	
	signalCH := comm.InitSignal()
	comm.HandleSignal(signalCH)
}